﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using UcAsp.Net.Interface;
using System.Text.RegularExpressions;
using System.Threading;
using UcAsp.Net.Extract.Plug.QQ.BLL;
using UcAsp.Net.Extract.Plug.QQ.Model;
using HtmlAgilityPack;
using Newtonsoft.Json;
using System.IO;
namespace UcAsp.Net.Extract.Plug.QQ
{
    public partial class UcAspControl : UserControl, IExtract
    {
        private string domain = "www.hzspace.com";
        string secrity = UcAsp.Net.Comm.Encrypt.EncodeEncrypt("d4ae69128c0552305c8c23f210d158d2");
        private delegate void DelegateUpdate(string i);
        private DateTime _adddatetime = DateTime.Now;
        private Thread t;
        #region 属性
        /// <summary>
        /// 常规项
        /// </summary>
        /// 
        public string Security { get; set; }
        public string Image { get; set; }
        public int ID { get; set; }
        public string Title { get; set; }
        public string Tag { get; set; }
        public string IconUrl { get; set; }
        public string ArticleContent { get; set; }
        public string MetaKeyword { get; set; }
        public string MetaDescrition { get; set; }
        public string Description { get; set; }
        public DateTime AddDatetime { get { return this._adddatetime; } set { this._adddatetime = value; } }
        public bool IsRelease { get; set; }
        public bool IsRecommend { get; set; }
        public int Hot { get; set; }
        public int Rate { get; set; }
        public int CategorieID { get; set; }
        public string ShowPath { get; set; }
        public string ViewsTemp { get; set; }
        public int UserID { get; set; }
        public int Rank { get; set; }

        /// <summary>
        /// 可变文字项
        /// </summary>
        public string Note1 { get; set; }
        public string Note2 { get; set; }
        public string Note3 { get; set; }
        public string Note4 { get; set; }
        public string Note5 { get; set; }
        public string Note6 { get; set; }
        public string Note7 { get; set; }
        public string Note8 { get; set; }
        public string Note9 { get; set; }
        /// <summary>
        /// 可变数组项
        /// </summary>
        public int Int1 { get; set; }
        public int Int2 { get; set; }
        public int Int3 { get; set; }
        public int Int4 { get; set; }
        public int Int5 { get; set; }


        public double Float1 { get; set; }
        public double Float2 { get; set; }
        public double Float3 { get; set; }
        public double Float4 { get; set; }
        public double Float5 { get; set; }


        public DateTime Date1 { get; set; }
        public DateTime Date2 { get; set; }
        public DateTime Date3 { get; set; }
        public DateTime Date4 { get; set; }
        public DateTime Date5 { get; set; }
        public DateTime Date6 { get; set; }
        public DateTime Date7 { get; set; }
        public DateTime Date8 { get; set; }
        public int PageCount { get; set; }
        #endregion
        public virtual bool Execute(object id)
        { return true; }
        public virtual object Init() { return new bool(); }
        public event EventHandler Save;
        public event EventHandler SavePage;
        public event EventHandler SaveImage;
        public UcAspControl()
        {
            InitializeComponent();
        }

        private void UcAspControl_Load(object sender, EventArgs e)
        {
            List<Model.Config> list = BLL.Config.GetListConfig;
            lbConfig.DataSource = list;
            lbConfig.DisplayMember = "DefinedTitle";
            lbConfig.ValueMember = "DefinedName";

            this.Width = this.Parent.Width;
            this.Height = this.Parent.Height;
        }
        public void UpdateData(object path)
        {

            Model.FilesConfig config = BLL.FilesConfig.GetFilesConfig(path.ToString());
            for (int p = config.PageNumber; p > 0; p--)
            {
                string urlcongent = string.Empty;
                if (p != 0)
                {
                    urlcongent = HttpWebClient.GetString(config.PageUrl.Replace("{page}", p.ToString()));
                }
                else
                {
                    urlcongent = HttpWebClient.GetString(config.Url);
                }
                this.Invoke(new Action(delegate
                {
                    label1.Text = string.Format("第{0}页", p);
                }));
                HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
                document.LoadHtml(urlcongent);
                HtmlNodeCollection c = document.DocumentNode.SelectNodes(config.txtURLReg);
                int contentnumber = 1;
                foreach (HtmlNode n in c)
                {

                    string url = n.Attributes["href"].Value;
                    HtmlAgilityPack.HtmlDocument icoPack = new HtmlAgilityPack.HtmlDocument();
                    icoPack.LoadHtml(n.InnerHtml);
                    HtmlNode im = icoPack.DocumentNode.SelectSingleNode("/img");
                    string img = im.Attributes["src"].Value;
                    string title = im.Attributes["alt"].Value;


                    IconUrl = "";

                    byte[] ico = BLL.HttpWebClient.GetImage(img);

                    if (ico != null)
                    {
                        IDictionary<object, object> param = new Dictionary<object, object>();
                        string filetext = BLL.HttpWebClient.HttpPost("http://" + domain + "/UploadFile.ashx?Security=" + secrity + "", param, ico, img);
                        if (filetext == null)
                        {
                            Thread.Sleep(1000 * 65*2);
                            filetext = BLL.HttpWebClient.HttpPost("http:/" + domain + "/UploadFile.ashx?Security=" + secrity + "", param, ico, img);
                        }
                        if (!string.IsNullOrEmpty(filetext))
                        {
                            JsonReader filejson = new JsonTextReader(new StringReader(filetext));
                            JsonSerializer serializer = new JsonSerializer();
                            FileModel filemodel = (FileModel)serializer.Deserialize(filejson, typeof(FileModel));
                            if (filemodel.status == "true")
                            {
                                IconUrl = filemodel.filepath;
                            }
                        }
                    }



                    Title = title;

                    string pagecontent = HttpWebClient.GetString(config.RootPath + url);
                    HtmlAgilityPack.HtmlDocument pagedocument = new HtmlAgilityPack.HtmlDocument();
                    pagedocument.LoadHtml(pagecontent);
                    string pagedocmenthtml = pagedocument.DocumentNode.SelectSingleNode(config.ContentReg).InnerHtml;

                    RegexOptions options = RegexOptions.None;
                    Regex regex = new Regex(config.ClearReg, options);
                    string result = regex.Replace(pagedocmenthtml, "");

                    HtmlNode descenote = pagedocument.DocumentNode.SelectSingleNode(config.DescReg);
                    if (descenote != null)
                    {
                        string desce = descenote.InnerText;
                        Description = desce;
                        string htmldesc = descenote.OuterHtml;
                        result = result.Replace(htmldesc, "");
                    }
                    ArticleContent = result;
                    AddDatetime = DateTime.Now; CategorieID = config.CategorieID; IsRelease = true; Image = config.ImageReg;
                    PageCount = 0;
                    //分页
                    HtmlNodeCollection page = pagedocument.DocumentNode.SelectNodes(config.PageReg);
                    if (page != null)
                    { PageCount = page.Count; }

                    if (Save != null)
                    {
                        Save(this, EventArgs.Empty);
                        Thread.Sleep(1000);
                    }

                    if (page != null)
                    {

                        int pagenumber = 2;
                        foreach (HtmlNode node in page)
                        {
                            string pageurl = node.Attributes["href"].Value;
                            string number = node.InnerText;
                            if (IsNumber(number))
                            {

                                Int1 = pagenumber;
                                SmallContent(pageurl, config, Title, Int1, IconUrl);
                                this.Invoke(new Action(delegate
                                {
                                    label2.Text = string.Format("第{0}页", pagenumber);
                                }));

                                pagenumber++;
                            }
                            Thread.Sleep(1000);
                        }
                    }
                    ID = 0;
                    this.Invoke(new Action(delegate
                    {
                        label3.Text = string.Format("第{0}片", contentnumber);
                    }));
                    contentnumber++;
                    Thread.Sleep(1000);
                }
                Thread.Sleep(2000);
            }

        }
        private void SmallContent(string url, Model.FilesConfig config, string title, int pagenumber, string icourl)
        {
            string pagecontent = HttpWebClient.GetString(config.RootPath + url);
            HtmlAgilityPack.HtmlDocument pagedocument = new HtmlAgilityPack.HtmlDocument();
            pagedocument.LoadHtml(pagecontent);
            string pagedocmenthtml = pagedocument.DocumentNode.SelectSingleNode(config.ContentReg).InnerHtml;

            RegexOptions options = RegexOptions.None;
            Regex regex = new Regex(config.ClearReg, options);
            string result = regex.Replace(pagedocmenthtml, "");
            Title = title;
            Int1 = pagenumber;
            IconUrl = icourl;
            HtmlNode descenote = pagedocument.DocumentNode.SelectSingleNode(config.DescReg);
            if (descenote != null)
            {
                string desce = descenote.InnerText;
                string htmldesc = descenote.OuterHtml;
                result = result.Replace(htmldesc, "");
            }
            Title = title;
            ArticleContent = result;

            if (SavePage != null)
            {
                SavePage(this, EventArgs.Empty);
                Thread.Sleep(1000);
            }
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            // UpdateData(lbConfig.SelectedValue);
            if (lbConfig.SelectedValue != null)
            {
                label1.Show();
                ParameterizedThreadStart start = new ParameterizedThreadStart(UpdateData);

                t = new Thread(start);
                t.Name = "updatedata";
                t.Start(lbConfig.SelectedValue.ToString());
                t.IsBackground = true;
                // UpdateData(lbConfig.SelectedValue.ToString());
            }
            else
            {
                MessageBox.Show("请选择更新类目");
            }
        }

        private bool IsNumber(string number)
        {
            if (string.IsNullOrEmpty(number))
                return false;
            else
            {
                try
                {
                    int.Parse(number);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (t != null)
            {
                t.Abort();
            }
        }
    }
}
